package mvv.learn.spring.dao.elasticsearch;

import java.util.List;

import mvv.learn.spring.dto.elasticsearch.ElsAbsDto;
import mvv.learn.spring.dto.elasticsearch.ElsEmployeeDto;
import mvv.learn.spring.dto.elasticsearch.ElsIndexingResponse;
import mvv.learn.spring.utitilies.AppParam;
import mvv.learn.spring.utitilies.RequestUtilities;

import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Repository;
/**
 * @author Manh Vu
 */
@Repository
public class ElasticsearchDao {

	@Autowired
	private ElasticsearchConfig elasticsearchConfig;

	private String baseUrl;

	protected Client getClient() {
		return elasticsearchConfig.getClient();
	}

	protected ElasticsearchTemplate elasticsearchTemplate() {
		return elasticsearchConfig.getElasticsearchTemplate();
	}

	public List<ElsEmployeeDto> getListElsEmployeeDto() {
		QueryBuilder builder = QueryBuilders
				.queryString("123").field("phoneNumber").field("employeeId")
				; // "phoneNumber", "423"

		//@formatter:off
		SearchQuery searchQuery = new NativeSearchQueryBuilder()
			.withIndices(ElasticsearchConstant.I_EMPLOYEE)
			.withTypes(ElasticsearchConstant.T_EMPLOYEE)
			.withQuery(builder)
			.build();
		//@formatter:on

		return elasticsearchTemplate().queryForList(searchQuery, ElsEmployeeDto.class);
	}

	public <D> boolean indexDocument(ElsAbsDto dto, Class<D> clazz) {
		IndexQuery indexQuery = new IndexQuery();
		indexQuery.setId(dto.getId());
		indexQuery.setObject(dto);

		// creating mapping
		elasticsearchTemplate().putMapping(clazz);

		// indexing document
		elasticsearchTemplate().index(indexQuery);

		// refresh
		elasticsearchTemplate().refresh(clazz, true);

		return true;
	}

	public ElsIndexingResponse indexDocument(ElsAbsDto dto, String urlType) {
		// index document
		StringBuilder sb = new StringBuilder(urlType);
		sb.append(AppParam.VAL_SLASH).append(dto.getId());

		ElsIndexingResponse res = RequestUtilities.getRestTemplate().postForObject(sb.toString(), dto, ElsIndexingResponse.class);

		return res;
	}

	public boolean createIndex(String urlIndex) {
		// create index
		RequestUtilities.getRestTemplate().put(urlIndex, null);

		return true;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public String getBaseUrl() {
		return baseUrl;
	}
}
